from typing import List
from pydantic import BaseModel
from fastapi import APIRouter, HTTPException, status
from starlette.responses import JSONResponse

from api.deps import db_dependency, user_dependency
from api.models import Article

router = APIRouter(
    prefix="/articles",
    tags=["articles"],
)


class ArticleBase(BaseModel):
    title: str
    content: str


class ArticleCreate(ArticleBase):
    pass


class ArticleResp(ArticleBase):
    id: int


@router.get("", response_model=List[ArticleResp])
async def get_article_list(db: db_dependency, user: user_dependency):
    articles = db.query(Article).filter(
        Article.user_id == user.id,
    ).all()
    return articles


@router.post("", status_code=status.HTTP_201_CREATED)
async def create_article(db: db_dependency, user: user_dependency, create_article_request: ArticleCreate):
    # 检查文章标题唯一性
    if db.query(Article).filter(
            Article.title == create_article_request.title,
            Article.user_id == user.id,
    ).first():
        raise HTTPException(
            status_code=status.HTTP_409_CONFLICT,
            detail="Article title already exists",
        )

    # 创建文章
    try:
        create_article_model = Article(
            title=create_article_request.title,
            content=create_article_request.content,
            user_id=user.id,
        )
        db.add(create_article_model)
        db.commit()
        db.refresh(create_article_model)
        return JSONResponse(
            content={
                "id": create_article_model.id,
                "title": create_article_model.title,
                "content": create_article_model.content,
            },
            status_code=status.HTTP_201_CREATED
        )
    except Exception as e:
        db.rollback()
        raise HTTPException(
            status_code=status.HTTP_500_INTERNAL_SERVER_ERROR,
            detail="Failed to create user"
        )


@router.delete("/{article_id}")
async def delete_article(db: db_dependency, user: user_dependency, article_id: int):
    article = db.query(Article).filter(
        Article.id == article_id,
        Article.user_id == user.id,
    ).first()
    if not article:
        raise HTTPException(status_code=status.HTTP_404_NOT_FOUND, detail="Article not found or access denied")
    db.delete(article)
    db.commit()
    return {"message": "Article deleted successfully"}


@router.get("/{article_id}", response_model=ArticleResp)
async def get_article(db: db_dependency, user: user_dependency, article_id: int):
    article = db.query(Article).filter(
        Article.id == article_id,
        Article.user_id == user.id,
    ).first()
    if not article:
        raise HTTPException(status_code=status.HTTP_404_NOT_FOUND, detail="Article not found or access denied")
    return article
